package com.example.store2.Service.impl;

import com.example.store2.Mapper.ResourcesMapper;
import com.example.store2.Mapper.URMapper;
import com.example.store2.Mapper.UserMapper;
import com.example.store2.Service.ResourcesService;
import com.example.store2.pojo.PageBean;
import com.example.store2.pojo.Resources;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ResourcesServiceImpl implements ResourcesService {
    @Autowired
    private ResourcesMapper resourcesMapper;
    @Autowired
    private URMapper urMapper;
    @Autowired
    private UserMapper userMapper;
    /**
     * 分页查询我的所有资源
     * @param page
     * @param pageSize
     * @param classesId
     * @param resourcesName
     * @return
     */
    @Override
    public PageBean list(Integer page, Integer pageSize,Integer id, Integer classesId, String resourcesName) {
        PageHelper.startPage(page,pageSize);
        List<Resources> e=resourcesMapper.list(id,classesId,resourcesName);
        Page<Resources> p=(Page<Resources>) e;
        PageBean pageBean=new PageBean(p.getTotal(),p.getResult());
        return pageBean;
    }
    /**
     * 添加资源
     * @param resources
     * @return
     */
    @Override
    public boolean add(Resources resources) {
        Integer number=urMapper.count(resources);
        if(number< userMapper.getbyid(resources.getUserId())*30){
            resourcesMapper.add(resources);
            resources.setId(resourcesMapper.nowadd());
            urMapper.add(resources);
            return true;
        }
        return false;
    }
    /**
     * 删除资源
     * @param id
     * @return
     */
    @Override
    public void delete(Integer id) {
        urMapper.delete(id);
        resourcesMapper.delete(id);
    }
    /**
     * 修改资源
     * @param resources
     * @return
     */
    @Override
    public void update(Resources resources) {
        String state=urMapper.find(resources);//寻找当前查找的资源是否是开源
        resourcesMapper.update(resources);
        if(!state.equals(resources.getState()))//当 当前资源状态和修改后资源状态不同的时候才需要对ur表进行修改
        {
            resources.setUpdateTime(LocalDateTime.now());
            urMapper.update(resources);
            if(state.equals("开源")&&resources.getState().equals("私有")){
                List<Integer>e =urMapper.list(resources);
                for(Integer id :e){
                    urMapper.deletebystate(id);
                }
            }
        }


    }


}
